/**
 * Apr 29, 2010
 */
package org.tomale.id.inventory.management;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.preference.IPreferenceStore;
import org.tomale.id.ProviderException;
import org.tomale.id.common.KeyValuePair;
import org.tomale.id.inventory.management.Activator;
import org.tomale.id.inventory.management.IInventoryProvider;
import org.tomale.id.inventory.management.ui.preferences.PreferenceConstants;

/**
 * @author ferd
 *
 */
public class InventoryManager {
	
	public static final String EXT_ID_PROVIDER = "org.tomale.id.inventory.management.provider";

	private static InventoryManager _manager;
	private IInventoryProvider _provider;
	
	private InventoryManager(){
		
	}
	
	public static InventoryManager getInstance(){
		if(_manager == null){
			_manager = new InventoryManager();
		}
		return _manager;
	}
	
	public IInventoryProvider getProvider() throws ProviderException { 
		if(_provider == null){
			IPreferenceStore store = Activator.getDefault().getPreferenceStore();
			String id = store.getString(PreferenceConstants.PROVIDER_ID);
			IConfigurationElement[] elems = Platform.getExtensionRegistry().getConfigurationElementsFor(EXT_ID_PROVIDER);
			for(IConfigurationElement elem : elems){
				if(id.equals(elem.getAttribute("class"))){
					try {
						Object o = elem.createExecutableExtension("class");
						if(o instanceof IInventoryProvider){
							return (IInventoryProvider) o;
						} else {
							throw new ProviderException("Unable to create Inventory provider.");
						}
					}catch(CoreException e){
						Activator.logError(MessageFormat.format("Unable to create an instance of {0}.", id));
						throw new ProviderException("Unable to create provider.",e);
					}
				}
			}
			Activator.logError("No inventory provider configured.");
			throw new ProviderException("No inventory provider configured.");
		}
		return _provider;
	}
	
	public static List<KeyValuePair<String, String>> getProviders() {
		ArrayList<KeyValuePair<String, String>> ret = new ArrayList<KeyValuePair<String,String>>();
		IConfigurationElement[] elems = Platform.getExtensionRegistry().getConfigurationElementsFor(EXT_ID_PROVIDER);
		for(IConfigurationElement elem : elems){
			ret.add(new KeyValuePair<String, String>(elem.getAttribute("class"), 
					elem.getAttribute("description")));
		}
		return ret;
	}
}
